<template>
  <el-dialog v-model="centerDialogVisible" title="提交订单" width="820" align-center>
    <el-row>
      <el-col :span="24">
        <!-- 订单确认 -->
        <el-form :model="infoForm" label-width="100px">
          <el-form-item label="商品名称:">
            <el-row>
              <el-col>
                <span style="color:rgb(64, 158, 255);" v-if="payWay === '立即购买'">《{{ book.title }}》×{{ count }}</span>
                <div style="color:rgb(64, 158, 255);" v-if="payWay === '购物车结算'">
                  <span v-for="(item, index) in selectedBookList" :key="index">
                    《{{ item.bookDetail.title }}》×{{ item.quantity }}
                  </span>
                </div>
              </el-col>
            </el-row>
          </el-form-item>

          <el-form-item label="价格:">
            <el-row>
              <el-col>
                <span style="color:rgb(200, 0, 0);" v-if="payWay === '立即购买'">{{ totalAmountBuyNow() }}元</span>
                <span style="color:rgb(200, 0, 0);" v-if="payWay === '购物车结算'">{{ totalAmount }}元</span>
              </el-col>
            </el-row>

          </el-form-item>


          <el-form-item label="收货信息:">
            <el-select v-model="infoForm.addressId" placeholder="选择收货信息" size="large">
              <el-option v-for="item in addressList" :key="item.addressId"
                :label="'收货人：' + item.consignee + '，手机号：' + item.phone + '，地址：' + item.province + ',' + item.city + ',' + item.district + ',' + item.detail"
                :value=item.addressId />
            </el-select>
          </el-form-item>

          <el-form-item label="新地址：">
            <div>
              <el-button type="primary" @click="addAddressButton">添加地址</el-button>
              <AddressDialog v-model="addressVisible" @confirm="handleAddressConfirm" />
            </div>
          </el-form-item>

          <el-form-item label="支付方式:">
            <el-radio-group v-model="infoForm.payType">
              <el-radio v-for="(item, index) in payType" :key="index" :value="index + 1">{{ item }}</el-radio>

            </el-radio-group>
          </el-form-item>
        </el-form>


      </el-col>
    </el-row>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="delayPayment">稍后支付</el-button>
        <el-button type="primary" @click="confirmPayment">
          现在支付
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref } from 'vue';
import { watch, defineProps, defineEmits } from 'vue';
import { useUserStore } from '@/stores/user'
import AddressDialog from '@/components/user/addAddressDialog.vue'
import { userOrderStore } from '@/stores/order';
import { useRouter } from 'vue-router';
import { Decimal } from 'decimal.js'
import { ElMessage } from 'element-plus';

const orderStore = userOrderStore();
const router = useRouter();

const userStore = useUserStore();

//父组件传递过来的


const props = defineProps({
  payWay: {
    type: String,
    required: true,
  },
  book: {
    type: Object,
    // required: true,
  },
  count: {
    type: Number,
    // required: true,
  },

  dialogVisible: {
    type: Boolean,
    required: true,
  },
  cartIdList: {
    type: Array,
    // required: true,
  },
  selectedBookList: {
    type: Array,
    // required: true,
  },
  totalAmount: {
    type: Number,
    // required: true,
  },

});


//立即购买的商品价格
const totalAmountBuyNow = () => {
  const price = new Decimal(props.book.price.toString());
  const quantity = new Decimal(props.count.toString());
  return price.times(quantity).toFixed(2);
};

// 使用 v-model:dialogVisible 的值
const centerDialogVisible = ref(props.dialogVisible);

// 监听 dialogVisible 的变化
watch(() => props.dialogVisible, (newVal) => {
  centerDialogVisible.value = newVal;
});

// 同步子组件的值回父组件
const emit = defineEmits(['update:dialogVisible']);

watch(centerDialogVisible, (newVal) => {
  if (newVal === true) {
    getUserAddress()
  }
  emit('update:dialogVisible', newVal);

});

// 订单详情
const infoForm = ref({
  addressId: '',
  payType: 1
});

// 保存后台地址
const addressList = ref([]);
const payType = ref(['支付宝', '微信', '银行卡']);
// 获取用户地址
const getUserAddress = async () => {
  await userStore.fetchUserAddress();
  addressList.value = userStore.userAddress;
  //console.log("获取用户地址", addressList.value);
  if (addressList.value.length > 0) {
    // 查找默认地址
    const defaultAddress = addressList.value.find(addr => addr.isDefault);
    // 设置默认值，没有默认地址就显示第一个地址
    infoForm.value.addressId = defaultAddress ? defaultAddress.addressId : addressList.value[0].addressId;
  }
}
//添加地址弹窗
const addressVisible = ref(false);
const addAddressButton = () => {
  addressVisible.value = true

}
// 处理新地址添加后的确认事件
const handleAddressConfirm = () => {
  // 更新地址列表
  getUserAddress()
};

// 支付相关
const delayPayment = () => {
  if (props.payWay === '立即购买' && (infoForm.value.addressId !== '')) {


    console.log("点击稍后支付");
    const orderData = {
      bookId: props.book.bookId,
      quantity: props.count,
      addressId: infoForm.value.addressId,
      orderStatus: 1, // 订单状态1为待支付
      payMethod: infoForm.value.payType,
    }
    console.log("订单详情!!", orderData);
    // 调用支付接口
    orderStore.createOrderBuyOneBook(orderData)
    centerDialogVisible.value = false;
    router.push('/myOrderLists')
  } else if (props.payWay === '购物车结算' && (infoForm.value.addressId !== '')) {
    // 购物车结算
    console.log("购物车结算");
    const orderData = {
      CartIds: props.cartIdList,
      addressId: infoForm.value.addressId,
      orderStatus: 1, // 订单状态1为待支付
      payMethod: infoForm.value.payType,
    }
    console.log("购物车结算订单详情", orderData);
    // 调用支付接口
    orderStore.createOrderCart(orderData)
    centerDialogVisible.value = false;
    router.push('/myOrderLists')

  } else {
    ElMessage.error('请选择收货地址');
  }
  // router.push('/myOrderLists')
  // window.location.reload();

  // router.push("/shoppingCart")
}

const confirmPayment = async () => {
  if (props.payWay === '立即购买' && (infoForm.value.addressId !== '')) {
    console.log("确认支付");
    // centerDialogVisible.value = false;
    const orderData = {
      bookId: props.book.bookId,
      quantity: props.count,
      addressId: infoForm.value.addressId,
      orderStatus: 2, // 订单状态2为待发货
      payMethod: infoForm.value.payType,
    }
    console.log("确认支付订单详细", orderData);
    // 调用支付接口
    await orderStore.createOrderBuyOneBook(orderData)
    router.push('/myOrderLists')
    centerDialogVisible.value = false;
  } else if (props.payWay === '购物车结算' && (infoForm.value.addressId !== '')) {
    // 购物车结算
    console.log("购物车结算");
    const orderData = {
      CartIds: props.cartIdList,
      addressId: infoForm.value.addressId,
      orderStatus: 2, // 订单状态1为待支付
      payMethod: infoForm.value.payType,
    }
    console.log("购物车确认支付订单详细", orderData);
    orderStore.createOrderCart(orderData)
    router.push('/myOrderLists')
    // router.push("/shoppingCart")
    // window.location.reload();

    centerDialogVisible.value = false;
  } else {
    ElMessage.error('请选择收货地址');
  }



};


</script>

<style scoped></style>